<template>
  <view class="container" v-if="!loading">
    <view>
      <u-tabs-swiper
        ref="tabs"
        :list="tabsList"
        :is-scroll="false"
        :current="current"
        duration=""
        @change="tabsChange"
        bar-width="100"
      ></u-tabs-swiper>
    </view>

    <view class="h-100" style="">
      <swiper
        style="height: 80vh"
        :current="swiperCurrent"
        @transition="transition"
        @animationfinish="animationfinish"
      >
        <swiper-item class="swiper-item">
          <scroll-view scroll-y class="h-100" style="width: 100%">
            <!-- 商品页面 -->
            <view class="main h-100" v-if="goods.length">
              <!-- 头部 -->
              <view class="nav">
                <view class="header">
                  <view class="left" v-if="orderType == 'takein'">
                    <view class="store-name">
                      <text>{{ store.name }}</text>
                      <view class="iconfont iconarrow-right"></view>
                    </view>
                    <view class="store-location">
                      <u-icon
                        label=""
                        class="mr-10"
                        size="30rpx"
                        name="map"
                      ></u-icon>
                      <text>距离您 {{ store.distance_text }} 米</text>
                    </view>
                  </view>
                  <!-- 外卖 -->
                  <view class="left overflow-hidden" v-else>
                    <view class="d-flex align-items-center overflow-hidden">
                      <!-- <image
                        src="/static/images/order/location.png"
                        style="width: 30rpx; height: 30rpx"
                        class="mr-10"
                      ></image> -->
                      <u-icon name="map" class="mr-10"></u-icon>
                      <view
                        class="font-size-extra-lg text-color-base font-weight-bold text-truncate"
                      >
                        {{ store.store_address }}
                      </view>
                    </view>
                    <view
                      class="font-size-sm text-color-assist overflow-hidden text-truncate"
                    >
                      由<text class="text-color-base" style="margin: 0 10rpx"
                        >{{ store.name }}(商家)</text
                      >配送
                    </view>
                  </view>
                  <view class="right">
                    <view
                      class="dinein"
                      :class="{ active: orderType == 'takein' }"
                      @tap="SET_ORDER_TYPE('takein')"
                    >
                      <text>自取</text>
                    </view>
                    <view
                      class="takeout"
                      :class="{ active: orderType == 'takeout' }"
                      @tap="SET_ORDER_TYPE('takeout')"
                    >
                      <text>外卖</text>
                    </view>
                  </view>
                </view>
                <!-- 优惠活动提示 -->
                <view class="coupon">
                  <!-- <text class="title">查看商家信息</text> -->
                  <text class="title">相关活动</text>
                  <u-icon name="arrow-right"></u-icon>
                </view>
              </view>
              <!--  头部结束  -->
              <view class="content">
                <!-- 左: 分类滚动 -->
                <scroll-view
                  class="menus"
                  :scroll-into-view="menuScrollIntoView"
                  scroll-with-animation
                  scroll-y
                >
                  <!-- 分类 -->
                  <view class="wrapper">
                    <view
                      class="menu"
                      :id="`menu-${category.categoryId}`"
                      :class="{
                        current: category.categoryId === currentCateId,
                      }"
                      v-for="category in categorys"
                      :key="category.categoryId"
                      @tap="handleMenuTap(category.categoryId)"
                    >
                      <text>{{ category.categoryName }}</text>
                      <!-- bug  -->
                      <view
                        class="dot"
                        v-show="menuCartNum(category.categoryId)"
                        >{{ menuCartNum(category.categoryId) }}</view
                      >
                    </view>
                  </view>
                </scroll-view>
                <!-- 右: 商品滚动 -->
                <scroll-view
                  class="goods"
                  scroll-with-animation
                  scroll-y
                  :scroll-top="cateScrollTop"
                  @scroll="handleGoodsScroll"
                >
                  <view class="wrapper">
                    <u-swiper id="ads" :list="ads" :interval="3000"></u-swiper>
                    <view class="list">
                      <!-- category begin -->
                      <view
                        class="category"
                        v-for="category in categorys"
                        :key="category.categoryID"
                        :id="`cate-${category.categoryID}`"
                      >
                        <view class="title">
                          <text>{{ category.categoryName }}</text>
                          <!-- <image :src="item.icon" class="icon"></image> -->
                        </view>
                        <view class="items">
                          <!-- 商品 begin -->
                          <view
                            class="good"
                            v-for="good in goods[0].list"
                            :key="good.id"
                            v-if="good.categoryName == category.categoryName"
                          >
                            <image
                              :src="good.defaultImg"
                              class="image"
                              @tap="showGoodDetailModal(good, good)"
                            ></image>
                            <view
                              class="right"
                              v-if="good.categoryName == category.categoryName"
                            >
                              <text class="name">{{ good.name }}</text>
                              <text class="tips">{{ good.description }}</text>
                              <view class="price_and_action">
                                <text class="price"
                                  >￥{{ good.basePrice }}</text
                                >
                                <!-- 可选规格 -->
                                <view
                                  class="btn-group"
                                  v-if="good.saleAttrList.length"
                                >
                                  <button
                                    type="primary"
                                    class="btn property_btn"
                                    hover-class="none"
                                    @tap="showGoodDetailModal(good, good)"
                                  >
                                    选规格
                                  </button>
                                  <view
                                    class="dot"
                                    v-show="goodCartNum(good.id)"
                                    >{{ goodCartNum(good.id) }}</view
                                  >
                                </view>
                                <!-- 不可选规格 -->
                                <view class="btn-group" v-else>
                                  <button
                                    type="primary"
                                    v-show="goodCartNum(good.id)"
                                    plain
                                    class="btn reduce_btn"
                                    size="mini"
                                    hover-class="none"
                                    @tap="handleReduceFromCart(good, good)"
                                  >
                                    <u-icon name="minus"></u-icon>
                                  </button>
                                  <view
                                    class="number"
                                    v-show="goodCartNum(good.id)"
                                  >
                                    <!-- 显示数量 -->
                                    {{ goodCartNum(good.id) }}
                                  </view>
                                  <button
                                    type="primary"
                                    class="btn add_btn"
                                    size="min"
                                    hover-class="none"
                                    @tap="handleAddToCart(category, good, 1)"
                                  >
                                    <u-icon name="plus"></u-icon>
                                  </button>
                                </view>
                              </view>
                            </view>
                          </view>
                          <!-- 商品 end -->
                        </view>
                      </view>
                      <!-- category end -->
                    </view>
                  </view>
                </scroll-view>
                <!-- goods list end -->
              </view>
              <!-- content end -->
            </view>

            <!-- 商品页面结束 -->
          </scroll-view>
        </swiper-item>
        <!-- 商家信息 -->
        <swiper-item class="swiper-item">
          <scroll-view scroll-y class="h-100" style="width: 100%">
            <!-- content -->

            <store-detail></store-detail>
          </scroll-view>
        </swiper-item>
      </swiper>
      <!--  商家信息 -->
    </view>

    <!-- 购物车栏 begin -->
    <view class="cart-box" v-show="cart.length > 0">
      <view class="mark" @tap="openCartPopup">
        <u-icon name="shopping-cart-fill" v-show="this.cart"></u-icon>
        <view class="tag">{{ getCartGoodsNumber }}</view>
      </view>
      <view class="price" @tap="openCartPopup">￥{{ getCartGoodsPrice }}</view>
      <button
        type="primary"
        class="pay-btn"
        @tap="toPay()"
        :disabled="disabledPay"
      >
        {{ disabledPay ? `差${spread}元起送` : "去结算" }}
      </button>
    </view>
    <!-- 购物车栏 end -->

    <!-- 商品详情模态框 begin -->
    <modal
      :show="goodDetailModalVisible"
      class="good-detail-modal"
      color="#5A5B5C"
      width="90%"
      custom
      padding="0rpx"
      radius="12rpx"
    >
      <view class="cover">
        <view v-if="good.imgUrls" class="detail-imgs">
          <u-swiper
            class="detail-imgs"
            :list="goodImgUrlsList"
            autoplay
            mode="number"
          ></u-swiper>
        </view>

        <view class="btn-group">
          <u-icon name="star" size="40" class="mr-20"></u-icon>
          <u-icon name="close" @tap="closeGoodDetailModal" size="40"> </u-icon>
        </view>
      </view>
      <scroll-view class="detail" scroll-y>
        <view class="wrapper">
          <view class="basic">
            <view class="name">{{ good.name }}</view>
            <view class="tips">{{ good.description }}</view>
          </view>
          <view class="properties" v-if="good.saleAttrList">
            <!-- 销售属性 -->
            <view
              class="property"
              v-for="(goodSaleName, goodSaleNameIndex) in goodSaleNames"
              :key="goodSaleName"
            >
              <view class="title">
                <text class="name">{{ goodSaleName }}</text>
                <!-- <view class="desc" v-if="item.desc">({{ item.desc }})</view> -->
              </view>
              <view class="values">
                <view
                  class="value"
                  v-for="saleAttr in good.saleAttrList"
                  :key="saleAttr.id"
                  :id="`saleAttr-${goodSaleNameIndex}-${saleAttr.id}`"
                  v-if="saleAttr.name == goodSaleName"
                  :class="{
                    default: goodSaleKeyValue.indexOf(saleAttr.id) != -1,
                  }"
                  @tap="changePropertyDefault(saleAttr, $event)"
                >
                  {{ saleAttr.attrValue }}
                </view>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
      <view class="action">
        <view class="left">
          <!-- <view class="props">
            已经选规格：
          </view> -->
          <view class="price">￥{{ goodTotalPrice }}</view>
          <!-- 显示 所选 -->
          <!-- <view class="props" v-if="getGoodSelectedProps(good)">
            以选规格：{{ getGoodSelectedProps(good) }}
          </view> -->
        </view>
        <view class="btn-group">
          <button
            type="primary"
            plain
            class="btn"
            size="mini"
            hover-class="none"
            @tap="handlePropertyReduce"
          >
            <u-icon name="minus"></u-icon>
          </button>
          <view class="number">{{ good.number }}</view>
          <button
            type="primary"
            class="btn add_btn"
            size="min"
            hover-class="none"
            @tap="handlePropertyAdd"
          >
            <u-icon name="plus"></u-icon>
          </button>
        </view>
      </view>
      <view class="add-to-cart-btn" @tap="handleAddToCartInModal">
        <view>加入购物车</view>
      </view>
    </modal>
    <!-- 商品详情模态框 end -->

    <!-- 购物车详情popup -->
    <popup-layer
      direction="top"
      :show-pop="cartPopupVisible"
      class="cart-popup"
      @openpopup="openCartPopup"
    >
      <template slot="content">
        <view class="top">
          <text @tap="handleCartClear">清空购物车</text>
        </view>
        <scroll-view class="cart-list" scroll-y>
          <view class="wrapper">
            <view class="item" v-for="(item, index) in cart" :key="index">
              <view class="left">
                <view class="left_good_img">
                  <u-image
                    width="100"
                    height="100"
                    :src="item.defaultImg || OrderItemImg(item.id)"
                  >
                  </u-image>
                </view>
                <view class="right_content">
                  <view class="name">{{ item.name }}</view>
                  <view class="props">{{ item.props_text }}</view>
                </view>
              </view>
              <view class="center">
                <text>￥{{ item.price }}</text>
              </view>
              <view class="right">
                <button
                  type="primary"
                  plain
                  size="mini"
                  class="btn"
                  hover-class="none"
                  @tap="handleCartItemReduce(index)"
                >
                  <u-icon name="minus"></u-icon>
                </button>
                <view class="number">{{ item.number }}</view>
                <button
                  type="primary"
                  class="btn"
                  size="min"
                  hover-class="none"
                  @tap="handleCartItemAdd(index)"
                >
                  <u-icon name="plus"></u-icon>
                </button>
              </view>
            </view>
            <!-- 外卖配送 👇 -->
            <view
              class="item"
              v-if="orderType == 'takeout' && store.packing_fee"
            >
              <view class="left">
                <view class="name">包装费</view>
              </view>
              <view class="center">
                <text>￥{{ parseFloat(store.packing_fee) }}</text>
              </view>
              <view class="right invisible">
                <button
                  type="default"
                  plain
                  size="mini"
                  class="btn"
                  hover-class="none"
                >
                  <view class="iconfont iconsami-select"></view>
                </button>
                <view class="number">1</view>
                <button
                  type="primary"
                  class="btn"
                  size="min"
                  hover-class="none"
                >
                  <view class="iconfont iconadd-select"></view>
                </button>
              </view>
            </view>
          </view>
        </scroll-view>
      </template>
    </popup-layer>
    <!-- 购物车详情popup end -->

    <!-- 清空购物车提示 -->
    <u-modal
      v-model="showModal"
      :mask-close-able="true"
      :show-cancel-button="true"
      :content="showModalContent"
      @confirm="handleCartClearConfirm"
    ></u-modal>
    <u-toast ref="tips"></u-toast>
  </view>
  <view class="loading" v-else>
    <image src="/static/images/loading.gif"></image>
  </view>
</template>

<script>
import modal from "@/components/modal/modal";
import popupLayer from "@/components/popup-layer/popup-layer";
import storeDetail from "@/components/store-detail/store-detail";

import { mapState, mapMutations, mapActions, mapGetters } from "vuex";

export default {
  components: {
    modal,
    popupLayer,
    storeDetail,
  },
  data() {
    return {
      tabsList: [{ name: "商品信息" }, { name: "商家详情" }],
      current: 0, // tab current 活动tab
      swiperCurrent: 0, // 页面 current
      dx: 0,
      goods: [], // 在  v-for 中使用 goods[0]
      categoryName: [],
      // goods:[],
      ads: [
        {
          image:
            "https://img-shop.qmimg.cn/s23107/2020/04/27/4ebdb582a5185358c4.jpg?imageView2/2/w/600/h/600",
        },
        {
          image:
            "https://images.qmai.cn/s23107/2020/05/08/c25de6ef72d2890630.png?imageView2/2/w/600/h/600",
        },
        {
          image:
            "https://img-shop.qmimg.cn/s23107/2020/04/10/add546c1b1561f880d.jpg?imageView2/2/w/600/h/600",
        },
        {
          image:
            "https://images.qmai.cn/s23107/2020/04/30/b3af19e0de8ed42f61.jpg?imageView2/2/w/600/h/600",
        },
        {
          image:
            "https://img-shop.qmimg.cn/s23107/2020/04/17/8aeb78516d63864420.jpg?imageView2/2/w/600/h/600",
        },
      ],
      loading: true,
      currentCateId: 0, //默认分类
      cateScrollTop: 0,
      menuScrollIntoView: "",
      cart: [], //购物车
      goodDetailModalVisible: false, //是否饮品详情模态框
      good: {}, //当前商品
      category: {}, //当前商品分类
      // goodTotalPiece:0,
      goodSaleNames: [],
      goodSaleKeyValue: [5, 9], // 当前商品销售属性键值对
      cartPopupVisible: false,
      sizeCalcState: false,
      showModal: false,
      showModalContent: "",
    };
  },
  async onLoad(option) {
    console.log("onload");
    await this.init();
    // if(option.show == 1){
    //   this.showModal = true;
    // }
  },
  computed: {
    ...mapState(["orderType", "address", "store"]),
    ...mapGetters(["isLogin", "getProduct"]),
    test() {
      console.log("tap.");
    },
    OrderItemImg() {
      // 获取 img
      // 从 全局
      return (id) => {
        return this.getProduct(id).defaultImg;
      };
    },
    // 通过 goods 收集分类信息
    categorys() {
      let goodlists = this.goods[0].list;
      let categorys = [];
      let _categorys = []; // temp
      for (let i = 0; i < goodlists.length; i++) {
        _categorys.push({
          categoryName: goodlists[i].categoryName,
          categoryId: goodlists[i].categoryId,
        });
      }
      // console.log(_categorys);
      categorys = this.unique(_categorys, "categoryId", "json");
      return categorys;
    },
    goodImgUrlsList() {
      // this.good 可以获取到 要被展开的good信息
      //
      // 拆分imgUrls 字段  return  list 给 v-for 渲染
      // return function(imgsStr){
      let _good = this.good;
      let _imgsList = _good.imgUrls;
      _imgsList = _imgsList.split(";");
      let imgsList = [];
      for (let i = 0; i < _imgsList.length; i++) {
        if (_imgsList[i] != "") {
          imgsList.push({
            image: `${_imgsList[i]}`,
          });
          //  _imgsList =  _imgsList.splice(0,i)
        }
      }

      // _imgsList.splice(0,_imgsList)
      // console.log(_imgsList);
      return imgsList;
      // }
    },
    goodTotalPrice() {
      // 从 detailModal 进入的当前价格计算
      let _totalPrice = this.good.basePrice;
      let saleAttrs = this.good.saleAttrList;
      if (saleAttrs) {
        for (let i = 0; i < saleAttrs.length; i++) {
          if (this.goodSaleKeyValue.indexOf(saleAttrs[i].id) != -1) {
            _totalPrice += saleAttrs[i].extraPrice;
          }
        }
      } else {
        return _totalPrice;
      }
      _totalPrice = _totalPrice * this.good.number;
      return _totalPrice;
    },
    goodCartNum() {
      // 购物车中单个商品的数量
      return (id) =>
        this.cart.reduce((acc, cur) => {
          if (cur.id === id) {
            return (acc += cur.number);
          }
          return acc;
        }, 0);
    },
    menuCartNum() {
      return (id) => {
        // let that = this;
        this.cart.reduce((acc, cur) => {
          if (cur.cate_id === id) {
            return (acc += cur.number);
          }
          return acc;
        }, 0);
      };
    },
    getCartGoodsNumber() {
      //计算购物车总数
      return this.cart.reduce((acc, cur) => acc + cur.number, 0);
    },
    getCartGoodsPrice() {
      //计算购物车总价
      return this.cart.reduce((acc, cur) => acc + cur.number * cur.price, 0);
    },
    disabledPay() {
      //是否达到起送价
      //
      return this.orderType == "takeout" &&
        this.getCartGoodsPrice < this.store.min_price
        ? true
        : false;
    },
    spread() {
      //差多少元起送
      if (this.orderType != "takeout") return;
      return parseFloat(
        (this.store.min_price - this.getCartGoodsPrice).toFixed(2)
      );
    },
  },
  onShow() {
    let user_id = this.$store.state.member.userId;
    this.cart = uni.getStorageSync("cart-" + user_id) || [];

    console.log("this.$store.state.showModal", this.$store.state.showModel);
    if (this.$store.state.showModel) {
      this.cartPopupVisible = true;
      this.$store.commit("SET_SHOWMODEL", false);
    }
    // setTimeout(() => {
    // }, 2000);
  },

  methods: {
    ...mapMutations(["SET_ORDER_TYPE", "SET_GOODS"]),
    ...mapActions(["getStore"]),
    // tab-swiper   切换效果
    tabsChange(index) {
      console.log(index);git 
      this.swiperCurrent = index;
    },
    // page 切换  改变 tab-swiper
    transition({ detail: { dx } }) {
      this.$refs.tabs.setDx(dx);
    },
    animationfinish({ detail: { current } }) {
      this.$refs.tabs.setFinishCurrent(current);
      this.swiperCurrent = current;
      this.current = current;
    },

    async init() {
      //页面初始化
      let that = this;
      that.loading = true;
      await that.getStore();
      let _goods = await this.$u.api.getALLgoods();
      that.goods = [_goods]; // 设置goods

      // 把商品信息添加进全局
      // store  order 页面会使用到商品图片
      _goods.list.forEach((ele) => {
        that.SET_GOODS(ele);
      });
      this.loading = false;

      const user_id = that.$store.state.member.userId;
      this.cart = uni.getStorageSync("cart-" + user_id) || [];
    },
    // 刷新购物车商品
    reFreshCart() {
      // 检查图片有无
      // this.cart
    },

    takout() {
      if (this.orderType == "takeout") return;

      if (!this.isLogin) {
        uni.navigateTo({ url: "/pages/login/login" });
        return;
      }

      uni.navigateTo({
        url: "/pages/address/address?is_choose=true",
      });
    },
    handleMenuTap(id) {
      //点击菜单项
      if (!this.sizeCalcState) {
        this.calcSize();
      }
      this.currentCateId = id;
      let domId = "menu-" + id;
      let query = uni.createSelectorQuery().in(this);
      let top = 0;
      query
        .select(`#${domId}`)
        .boundingClientRect(
          (data) => {
            console.log("得到布局位置信息" + JSON.stringify(data));
            console.log("节点离页面顶部的距离为" + data.top);
            top = data.top;
          },
          function (data) {
            console.log("节点的垂直滚动位置:" + data);
          }
        )
        .exec();

      this.$nextTick(() =>
        // (this.cateScrollTop = this.goods.find((item) => item.id == id).top)
        // (console.log(this.cateScrollTop))
        // (this.cateScrollTop = top)
        this.$nextTick(
          () =>
            // (this.cateScrollTop = this.categorys.find((item) => item.categoryID == id).top)
            (this.cateScrollTop = top)
        )
      );
    },
    handleGoodsScroll({ detail }) {
      //商品列表滚动事件
      if (!this.sizeCalcState) {
        this.calcSize();
      }
      const { scrollTop } = detail;
      let tabs = this.goods.filter((item) => item.top <= scrollTop).reverse();
      if (tabs.length > 0) {
        this.currentCateId = tabs[0].id;
      }
    },
    calcSize() {
      let h = 10;

      let view = uni.createSelectorQuery().select("#ads");
      view
        .fields(
          {
            size: true,
          },
          // data : width:xx height:xx
          (data) => {
            h += Math.floor(data.height);
          }
        )
        .exec();

      this.goods.forEach((item) => {
        let view = uni.createSelectorQuery().select(`#cate-${item.id}`);
        view
          .fields(
            {
              size: true,
            },
            (data) => {
              item.top = h;
              h += data.height;
              item.bottom = h;
            }
          )
          .exec();
      });
      this.sizeCalcState = true;
    },
    //添加到购物车
    handleAddToCart(cate, good, num) {
      let _goodTotalPrice = this.goodTotalPrice / num;
      const index = this.cart.findIndex((item) => {
        if (good.saleAttrList.length) {
          // return item.id === good.id && item.props_text === good.props_text;
          return item.id === good.id && item.props_text === good.props_text;
        } else {
          return item.id === good.id;
        }
      });
      if (index > -1) {
        this.cart[index].number += num;
      } else {
        //
        // 购物车 要显示的数据： name saleattrlist price+exprice number
        //  defaultImg
        //
        this.cart.push({
          name: good.name,
          id: good.id,
          number: num,
          content: good.description,
          defaultImg: good.defaultImg,
          props_text: good.props_text,
          props: good.props,
          price: _goodTotalPrice || good.basePrice,
          // saleAttrList:
        });
        // this.cart.push({
        //   id: good.id,
        //   cate_id: cate.id,
        //   name: good.name,
        //   price: good.price,
        //   number: num,
        //   image: good.images,
        //   use_property: good.use_property,
        //   props_text: good.props_text,
        //   props: good.props,
        // });
      }
    },
    handleReduceFromCart(item, good) {
      const index = this.cart.findIndex((item) => item.id === good.id);
      this.cart[index].number -= 1;
      if (this.cart[index].number <= 0) {
        this.cart.splice(index, 1);
      }
    },
    showGoodDetailModal(item, good) {
      this.good = JSON.parse(JSON.stringify({ ...good, number: 1 }));
      this.category = JSON.parse(JSON.stringify(item));
      // 商品的销售属性 用于 渲染 detailmodel
      this.goodSaleNames = this.setGoodSaleAttrName(
        JSON.parse(JSON.stringify(good))
      );
      // 用于保存商品的 销售属性键值对
      this.goodSaleKeyValue = this.setGoodSaleKeyValue(
        JSON.parse(JSON.stringify(good))
      );
      this.goodDetailModalVisible = true;
    },
    closeGoodDetailModal() {
      //关闭饮品详情模态框
      this.goodDetailModalVisible = false;
      this.category = {};
      this.good = {};
    },
    //  销售属性值 事件
    changePropertyDefault(saleAttr, e) {
      let _domID = e.currentTarget.id;
      let _index = _domID.split("-")[1];
      let _id = _domID.split("-")[2];
      // 响应式
      this.$set(this.goodSaleKeyValue, _index, parseInt(_id));
    },
    getGoodSelectedProps(good, type = "text") {
      // 商品已选择的规格
      // 显示在modal 和 购物车popup
      if (good.saleAttrList) {
        let props = [];
        good.saleAttrList.forEach((s) => {
          if (this.goodSaleKeyValue.indexOf(s.id) != -1) {
            console.log(s);
            props.push(type == "text" ? s.attrValue : s.id);
          }
        });
        return type === "text" ? props.join("，") : props;
      }
      return "";
    },
    handlePropertyAdd() {
      this.good.number += 1;
    },
    handlePropertyReduce() {
      if (this.good.number === 1) return;
      this.good.number -= 1;
    },
    handleAddToCartInModal() {
      const product = Object.assign({}, this.good, {
        props_text: this.getGoodSelectedProps(this.good),
        // props: this.getGoodSelectedProps(this.good, "id"),
        props: this.goodSaleKeyValue,
      });
      // 原始方法
      this.handleAddToCart(this.category, product, this.good.number);
      this.closeGoodDetailModal();
    },
    // 会被子组件  popupLayer  改变
    openCartPopup() {
      //打开/关闭购物车列表popup
      this.cartPopupVisible = !this.cartPopupVisible;
    },
    handleCartClear() {
      //清空购物车
      this.showModal = true;
      this.showModalContent = "确定清空购物车么";
    },
    handleCartClearConfirm() {
      this.cartPopupVisible = false;
      this.cart = [];
      uni.removeStorage({
        key: "cart-" + this.$store.state.member.userId,
      });
      if (this.cart.length == 0) {
        this.$refs.tips.show({
          title: "已清空购物车.",
          type: "suceess",
        });
      }
    },
    handleCartItemAdd(index) {
      this.cart[index].number += 1;
    },
    handleCartItemReduce(index) {
      if (this.cart[index].number === 1) {
        this.cart.splice(index, 1);
      } else {
        this.cart[index].number -= 1;
      }
      if (!this.cart.length) {
        this.cartPopupVisible = false;
      }
    },
    toPay() {
      if (!this.isLogin) {
        this.$refs.tips.show({
          title: "您还未登录, 现在去登录吧.",
          type: "primary",
          url: "/pages/login/login",
        });
        return;
      }

      // uni.showLoading({ title: "加载中" });
      let that = this;
      uni.setStorageSync(
        "cart-" + that.$store.state.member.userId,
        JSON.parse(JSON.stringify(this.cart))
      );

      uni.navigateTo({
        url: "/pages/pay/pay",
      });
      // uni.hideLoading();
    },

    unique(arr, att, type) {
      let array = [];
      if (type == "json") {
        for (let i = 0; i < arr.length; i++) {
          let isChage = true;
          // if()
          for (let j = 0; j < array.length; j++) {
            if (arr[i][att] == array[j][att]) {
              isChage = false;
            }
          }
          if (isChage) {
            array.push(arr[i]);
          }
        }
      } else if (type == "list") {
        arr = arr.sort();
        array.push(arr[0]);
        for (let i = 1; i < arr.length; i++) {
          if (arr[i] != arr[i - 1]) {
            array.push(arr[i]);
          }
        }
      }
      return array;
    },
    setGoodSaleAttrName(good) {
      let saleAttrs = good.saleAttrList;
      let _saleAttrNames = [];
      // console.log(good);
      for (let i = 0; i < saleAttrs.length; i++) {
        _saleAttrNames.push(saleAttrs[i].name);
      }
      _saleAttrNames = this.unique(_saleAttrNames, "", "list");
      return _saleAttrNames;
    },
    setGoodSaleKeyValue(good) {
      let attrs = good.saleAttrList;
      let names = this.goodSaleNames;

      let _idList = [];
      let _names = [];
      for (let i = 0; i < names.length; i++) {
        _names.push(names[i]);
      }
      // 先循环一遍 筛选出 默认 | 无
      for (let i = 0; i < attrs.length; i++) {
        if (attrs[i].attrValue == "默认" || attrs[i].attrValue == "无") {
          _idList.push(attrs[i].id);
          _names.splice(_names.indexOf(`${attrs[i].name}`), 1);
        }
      }
      // 没删掉的属性 就是没添加入idList的销售属性
      // 再执行一次循环添加未添加的属性
      if (_names.length != 0) {
        for (let i = 0; i < _names.length; i++) {
          for (let j = 0; j < attrs.length; j++) {
            if (attrs[j].name == _names[i]) {
              _idList.push(attrs[j].id);
              break;
            }
          }
        }
      }

      return _idList;
    },
  },
};
</script>

<style lang="scss" scoped>
@import "~@/pages/menu/menu.scss";
</style>
